package simulation;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import server.ServerConstants;

import client.RandomClient;


public class Simulation {
	private Logger logger;
	
	private static int id;

	public Simulation() {
		File file = new File("log.log");
		if (file.exists()) {
			file.delete();
		}
		logger = LoggerFactory.getLogger(Simulation.class);
		id = 0;
	}

	public void simulate() {
		RandomClient pool[] = new RandomClient[SimulationConstants.NUMBER_OF_CLIENTS];
		for(int i = 0; i < SimulationConstants.NUMBER_OF_CLIENTS; i++) {
			pool[i] = new RandomClient(ServerConstants.PORT_NUMBER,i);
		}
		
		logger.info("Starting clients");
		for(int i = 0; i < SimulationConstants.NUMBER_OF_CLIENTS; i++){
			pool[i].setHighLoad();
			pool[i].start();
		}
		logger.info("Simulation taking a nap for " + SimulationConstants.SIMULATION_LENGHT / 1000 + " seconds");
		int slept = 0;
		while(slept < SimulationConstants.SIMULATION_LENGHT){
			sleep(SimulationConstants.SIMULATION_LENGHT/SimulationConstants.INTERVALS);
			slept += SimulationConstants.SIMULATION_LENGHT/SimulationConstants.INTERVALS;
			logger.info("Completed " + slept/ 1000 + " seconds of " + SimulationConstants.SIMULATION_LENGHT / 1000);
		}

		logger.info("Done napping, stopping clients");
		for(int i = 0; i < SimulationConstants.NUMBER_OF_CLIENTS; i++){
			pool[i].close();
		}
		
		logger.info("Simulation done, check log.log file for the log on the server for performance statisicts");
	}

	public static void sleep(int time) {
		try {
			Thread.sleep(time);
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]) {
		Simulation sim = new Simulation();
		sim.simulate();
	}
	
	public synchronized static int getMessageId(){
		return id++;
	}
}
